﻿using AutoMapper;
using Dm;
using FinancialManagement.Application.Command.SaleContractCommand;
using FinancialManagement.Domain.Model;
using FinancialManagement.Infrstructre.Interface;
using MediatR;
using SqlSugar;

namespace FinancialManagement.Application.CommandHandler.SaleContractCommandHandlers
{
    public class SaleContractUpdCommandHandlers : IRequestHandler<SaleContractUpdCommand, int>
    {
        IMapper mapper;
        private readonly ISaleContractProductRepository SRep;
        private readonly ISaleContractRepository CRep;
        ISqlSugarClient db;

        public SaleContractUpdCommandHandlers(IMapper mapper, ISaleContractProductRepository SRep, ISaleContractRepository CRep, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.SRep = SRep;
            this.CRep = CRep;
            this.db = db;
        }


        public async Task<int> Handle(SaleContractUpdCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                var material = mapper.Map<SaleContract>(request.AddDtos);
                int Item = await CRep.UpdateAsync(material);
                foreach (var subpiece in request.AddDtos.SaleContractProductDto)
                {
                    SaleContractProduct items = new SaleContractProduct
                    {
                       SaleContractProductId=subpiece.SaleContractProductId,
                        SCcontractNumber= request.AddDtos.SCcontractNumber,
                        ProductId=subpiece.ProductId,
                        PName=subpiece.PName,
                        PNumber=subpiece.PNumber,
                        SCPNum=subpiece.SCPNum,
                        TaxPrice=subpiece.TaxPrice,
                        Discount=subpiece.Discount,
                        BillType=   subpiece.BillType,
                        DetailsPreferential=subpiece.DetailsPreferential,
                        TaxLines=subpiece.TaxLines,
                        DeliveryTime=subpiece.DeliveryTime,
                        SRemark=subpiece.SRemark,
                        SInventory=subpiece.SInventory,
                        AddName= subpiece.AddName,
                        AddTime= subpiece.AddTime,
                        Office_Id=request.AddDtos.Office_Id,
                        User_Id=request.AddDtos.User_Id

                    };
                    await SRep.UpdateAsync(items);

                }
                // 提交事务
                db.Ado.CommitTran();

                return 1;


            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }


        }
    }
}
